{% set title = 'Isolate Server' %}
{% extends "isolate/base.html" %}


{% block headers %}
<style>
  html, body {
    display: table;
    height: 100%;
    /* TODO(maruel): Figure out how to be able to keep margins! */
    margin: 0;
    overflow: hidden;
    width: 100%;
  }
  div.use_all_space {
    display: table-row;
    height: 100%;
    margin: 0;
    padding: 0;
    width: 100%;
  }

  iframe.use_all_space {
    height: 100%;
    margin: 0;
    padding: 0;
    width: 100%;
  }
</style>

<script type="text/javascript" src="third_party/pako/pako-0.2.3.min.js">
</script>
<script>
  if (typeof String.prototype.endsWith !== 'function') {
    String.prototype.endsWith = function(suffix) {
      return this.indexOf(suffix, this.length - suffix.length) !== -1;
    };
  }

  // Fetch the content, uncompress it if necessary, then write it to the iframe.
  function update() {
    // TODO(maruel): Add #namespace=namespace&hash=hash for copy-pastability
    // without forcing a page reload instead of forcing a reload.
    var hash = encodeURIComponent(document.getElementById('hash').value);
    var namespace = encodeURIComponent(
        document.getElementById('namespace').value);
    var url = '/content-gs/retrieve/' + namespace + '/' + hash;
    fetch(namespace, url);
    document.getElementById('generated_link').innerHTML = (
        '<a href="' + url + '">Link to ' + hash + '</a>');
  }

  function fetch(namespace, url) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'arraybuffer';
    xhr.onload = function(e) {
      if (this.status == 200) {
        post_process_async(
            namespace, new Uint8Array(this.response), write_to_iframe);
      } else {
        /* TODO(maruel): Handle load failure because 'No
          'Access-Control-Allow-Origin' header is present on the requested
          resource.' and print out tools/README-CORS.
        */
        alert(this.statusText);
      }
    };
    xhr.send();
  }

  function decompress_to_string_async(data, callback) {
    var bytes = pako.inflate(new Uint8Array(data));
    var bb = new Blob([bytes]);
    var f = new FileReader();
    f.onload = function(e) {
      callback(e.target.result);
    };
    f.readAsText(bb);
  }

  function post_process_async(namespace, data, callback) {
    // Note that -gzip is a misnomer, it's actually -deflate.
    if (namespace.endsWith('-gzip') || namespace.endsWith('-deflate')) {
      decompress_to_string_async(data, function(x) {
        // Now act as if the namespace was the default uncompressed one so
        // further processing can be done.
        post_process_async('default', x, callback);
      });
      return;
    }
    if (data[0] == 'P' && data[1] == 'K') {
      // TODO(maruel): Implement PKzip decoding to be able to list files?
      callback("Found a .zip file (" + data.length + " bytes)");
      return;
    }
    if (data[0] == '{') {
      // Assume a json file, pretty-print it.
      // TODO(maruel): Convert .isolated files to browsable file.
      // TODO(maruel): Catch exception and print data as-is in that case.
      var pretty = JSON.stringify(JSON.parse(data), null, 2);
      callback(pretty);
      return;
    }
    // Fallback.
    callback(data);
  }

  function write_to_iframe(data) {
    var ifrm = document.getElementById('content').contentDocument;
    ifrm.open();
    ifrm.write('<html><body><pre>' + data + '</pre></body></html>');
    ifrm.close();
  }
</script>
{% endblock %}


{% block body %}

<h1>File browser</h1>

Enter the namespace and hash of an object:<br>
<form id="form1" method="GET">
  <input id="namespace" name="namespace" value="{{namespace}}" /><br>
  <input id="hash" name="hash" maxlength=40 size=40 value="{{hash_value}}" />
  <br>
  <input type=submit value="Load item"/><br>
</form>
<p>
<div id="generated_link"> </div>
<p>
<div class="use_all_space">
  <iframe id="content" class="use_all_space" sandbox="allow-same-origin">
  </iframe>
</div>

{% endblock %}
